/**
 * @file mlplatform.js
 * @author wxf
 * @date 2018/12/01
 */

/**
 * 设置数据集特征的多选
 */
function dataset_label_acquire(callback, dataset_id) {
   $.get(Urls.resolve('storage_api_v1:dataset_detail', {pk: dataset_id})).done(function (data) {
       console.log(data);
       callback(data);
   }).fail(function () {
        alert('error');
    });
}

function dataset_label_div(data) {
    $("#att-result").empty();
    $.each(data.data.indexs, function () {
            var obj =
                '<div class="col-lg-3" data-width="20px">'+
                '   <div class="radio radio-info radio-inline">' +
                '       <input type="radio" value='+ this +' name="radioInline">' +
                '       <label for="inlineRadio1">' + this + '</label>' +
                '   </div>'+
                '</div>';
        $("#att-result").append(obj);
    });
}
function dataset_label_show(dataset_id) {
    dataset_label_acquire(function (data) {
        dataset_label_div(data);
    },dataset_id);
}

// 数据调用函数 初始数据集显示
function acquire_result(callback, query_type = 1, time_sort, page = 1) {
  $.get(Urls.resolve('storage_api_v1:dataset_list'),{
    'page':page,
  }).done(function (data) {
    console.log(data);
    callback(data);
  });
  // $.requestJSON({
  //     url: Urls.resolve('storage_api_v1:dataset_list'),
  //   // url: Urls.resolve('search_api_v1:dataset_query'),
  //   method: 'GET',
  //   param: {query_type: query_type, time_sort: time_sort, page: page},
  //   onSuccess(data) {
  //     console.log(data);
  //     callback(data);
  //   }
  //   //如果获取不成功怎么办
  // });
}

function export_dataset(did) {
  window.location.href = Urls.resolve('storage_api_v1:dataset_download', {pk: did});
}

function dataset_set_table_noValue(data) {
  $("#income_box").text(gettext("Nothing......"));
}

function dataset_set_table_hasValue(data) {
  // $("#table-value").val(data.data.datasets[0].filename);
  $("#income_box").empty();
  var obj =
      '      <table class="table-content" width="95%" border="0" align="center" cellspacing="0" cellpadding="8">\n' +
      '        <tr class="tr-title"  align="left">\n' +
      '          <td class="td-title-1 first">' + gettext('Name') + '</td>\n' +
      '          <td class="td-title-2 second">' + gettext('Rows') + '</td>\n' +
      '          <td class="td-title-3 third">' + gettext('Columns') + '</td>\n' +
      '          <td class="td-title-4 fourth">' + gettext('Author') + '</td>\n' +
      '          <td class="td-title-5 fifth">' + gettext('Submission Time') + '</td>\n' +
      '          <td class="td-title-6 sixth">' + gettext('Purpose') + '</td>\n' +
      '        </tr>';
  var currentPage = data.data.current_page;
  var numberOfPages = data.data.total_pages;
  var step = (currentPage - 1) * numberOfPages;
  $.each(data.data.results, function () {
    step++;
    obj +=
        '        <tr class="tr-body" align="left" id="' + this['id'] + '">\n' +
        '          <td class="td-body-1 first">' +
        '              <div class="radio">' +
        '                <label><input class="radio" type="radio" name="iCheck" value="' + this['id'] + '">' + this['title'] + '</label>' +
        '              </div>' +
        '          </td>\n' +
        '          <td class="td-body-2 second">' + this['rows'] + '</td>\n' +
        '          <td class="td-body-3 third">' + this['cols'] + '</td>\n' +
        '          <td class="td-body-6 sixth">' + this['author'] + '</td>\n' +
        '          <td class="td-body-7 seventh">' + this['upload_time'] + '</td>\n' +
        '          <td class="td-body-8 eigthth">' + this['purpose'] + '</td>\n' +
        '          <td class="td-body-1 ninth">' +
        '              <button class="btn btn-default btn-sm btn-download" data-id="' + this['id'] + '"' +
        '                  style="float:right"' +
        '                  type="button"' +
        '                  data-title="{{ meta.title }}" data-toggle="tooltip" data-placement="left"' +
        '                  onclick="export_dataset(' + this['id'] + ')"' +
        '                  title="' + gettext('Download now') + '">' +
        '                  <i class="fa fa-download"></i>' +
        '              </button>' +
        '          </td>\n' +
        '        </tr>';
  });

  obj += '</table>';
  $("#income_box").append(obj);

  $(".tr-body:even").hover(function () {
    $(this).css("background-color", "#DCDCDC");
  }, function () {
    $(this).css("background-color", "#F5F5F5");
  });
  $(".tr-body:odd").hover(function () {
    $(this).css("background-color", "#DCDCDC");
  }, function () {
    $(this).css("background-color", "#FFFFFF");
  });

  $(".tr-body").on('click', function () {
      dataset_id = $(this).attr("id");
      dataset_label_show(dataset_id);
  });
}

function dataset_show_all(query_type, time_sort) {
  acquire_result(function (data) {
    if (data.data.count === 0) {
      dataset_set_table_noValue(data);
    } else {
      dataset_set_table_hasValue(data);
      var paginator = $('#dataset_paginator');
      var options = {
        bootstrapMajorVersion: 3,
        currentPage: 1,
        numberOfPages: 5,
        totalPages: data.data.total_pages,
        onPageClicked: function (e, originalEvent, type, page) {
          acquire_result(dataset_set_table_hasValue, query_type, time_sort, page);
        }
      };
      if (options.totalPages > 1) {
        paginator.bootstrapPaginator(options);  // 仅大于一页时分页
      }
    }
  }, query_type, time_sort, page = 1)
}

//数据集搜索结果
function sort_result(callback, query_type = 1, time_sort, page) {
    if (text) {
          $.requestJSON({
            url: Urls.resolve('search_api_v1:dataset_query'),
            method: 'POST',
            data: {
                desc:true,
                page:page,
                query_dict: {
                    text: text
                }
            },
            silentError: true,
            onSuccess: function (data) {
              console.log(data);
                callback(data);
            },
            onError:function (data) {
              $.showModal({
                  title: gettext('ERROR') + ' ' + data.code,
                  message: gettext('An error has occurred! Please check your data and try again.')
              });
            }
          });
        }
}

function sort_set_table_hasValue(data) {
  // $("#table-value").val(data.data.datasets[0].filename);
  $("#income_box").empty();
  var obj =
      '      <table class="table-content" width="95%" border="0" align="center" cellspacing="0" cellpadding="8">\n' +
      '        <tr class="tr-title"  align="left">\n' +
      '          <td class="td-title-1 first">' + gettext('Name') + '</td>\n' +
      '          <td class="td-title-2 second">' + gettext('Rows') + '</td>\n' +
      '          <td class="td-title-3 third">' + gettext('Columns') + '</td>\n' +
      '          <td class="td-title-4 fourth">' + gettext('Author') + '</td>\n' +
      '          <td class="td-title-5 fifth">' + gettext('Submission Time') + '</td>\n' +
      '          <td class="td-title-6 sixth">' + gettext('Purpose') + '</td>\n' +
      '        </tr>';
  var currentPage = data.data.current_page;
  var numberOfPages = data.data.total_pages;
  var step = (currentPage - 1) * numberOfPages;
  $.each(data.data.result, function () {
    step++;
    obj +=
        '        <tr class="tr-body" align="left" id="' + this['id'] + '">\n' +
        '         <td class="td-body-1 first">' +
        '              <div class="radio">' +
        '                <label><input type="radio" name="iCheck" value="' + this['id'] + '">' + this['title'] + '</label>' +
        '              </div>' +
        '            </td>\n' +
        '          <td class="td-body-2 second">' + this['rows'] + '</td>\n' +
        '          <td class="td-body-3 third">' + this['cols'] + '</td>\n' +
        '          <td class="td-body-6 sixth">' + this['author'] + '</td>\n' +
        '          <td class="td-body-7 seventh">' + this['upload_time'] + '</td>\n' +
        '          <td class="td-body-8 eigthth">' + this['purpose'] + '</td>\n' +
        '          <td class="td-body-1 ninth">' +
        '              <button class="btn btn-default btn-sm btn-download" data-id="' + this['id'] + '"' +
        '                  style="float:right"' +
        '                  type="button"' +
        '                  data-title="{{ meta.title }}" data-toggle="tooltip" data-placement="left"' +
        '                  onclick="export_dataset(' + this['id'] + ')"' +
        '                  title="' + gettext('Download now') + '">' +
        '                  <i class="fa fa-download"></i>' +
        '              </button>' +
        '          </td>\n' +
        '        </tr>';
  });
  obj += '</table>';
  $("#income_box").append(obj);

  $(".tr-body:even").hover(function () {
    $(this).css("background-color", "#DCDCDC");
  }, function () {
    $(this).css("background-color", "#F5F5F5");
  });
  $(".tr-body:odd").hover(function () {
    $(this).css("background-color", "#DCDCDC");
  }, function () {
    $(this).css("background-color", "#FFFFFF");
  });

  $(".tr-body").on('click', function () {
      dataset_id = $(this).attr("id");
      dataset_label_show(dataset_id);
  });
}

function sort_show_all(query_type, time_sort) {
  sort_result(function (data) {
    // dataset_count(data);
    if (data.data.count == 0) {
      dataset_set_table_noValue(data);
    } else {
      sort_set_table_hasValue(data);
      var paginator = $('#dataset_paginator');
      var options = {
        bootstrapMajorVersion: 3,
        currentPage: 1,
        numberOfPages: 5,
        totalPages: data.data.total_pages,
        onPageClicked: function (e, originalEvent, type, page) {
          acquire_result(dataset_set_table_hasValue, query_type, time_sort, page);
        }
      };
      if (options.totalPages > 1) {
        paginator.bootstrapPaginator(options);  // 仅大于一页时分页
      }
    }
  }, query_type, time_sort, page = 1)
}

//提交
function param_submit() {
    var alg = $('input:radio[name="ra"]:checked').val();
    var dataset = Number($('input:radio[name="iCheck"]:checked').val());
    var alg_params = $('input:radio[name="radioInline"]:checked').val();
    if(alg == 'SVM'){
        var params={
            C:parseFloat($("#svm0").val()),
            kernel:$("#svm1").val(),
            decision_function_shape: $("#svm2").val(),
            max_iter: parseInt($("#svm3").val()),
            random_state:parseInt($("#svm4").val())
        };
    }
    if(alg == 'MLPC'){
        var params={
            activation:$("#layerp0").val(),
            solver:$("#layerp1").val(),
            alpha: parseFloat($("#layerp2").val()),
            learning_rate: $("#layerp3").val(),
            max_iter:parseInt($("#layerp4").val()),
            random_state:parseInt($("#layerp5").val())
        };
    }
    if(alg == 'GPC'){
        var params={
            max_iter_predict:parseInt($("#gausspro0").val()),
            random_state:parseInt($("#gausspro1").val()),
            multi_class: $("#gausspro2").val(),
        };
    }
    if(alg == 'Linear'){
        var params={
            fit_intercept:$("#logist0").val(),
            normalize:$("#logist1").val(),
            copy_X: $("#logist2").val(),
        };
    }
    if(alg == 'Bayes'){
        var params={
            n_iter:parseInt($("#bayes0").val()),
            fit_intercept:$("#bayes1").val(),
            normalize: $("#bayes2").val(),
            copy_X: $("#bayes3").val(),
        };
    }
    if(alg == 'Ridge'){
        var params={
            fit_intercept:$("#ridge0").val(),
            normalize:$("#ridge1").val(),
            copy_X: $("#ridge2").val(),
            max_iter: parseInt($("#ridge3").val()),
            solver:$("#ridge4").val(),
            random_state:parseInt($("#ridge5").val()),
        };
    }
    if(alg == 'KMeans'){
        var params={
            n_clusters:parseInt($("#kan0").val()),
            init:$("#kan1").val(),
            n_init: parseInt($("#kan2").val()),
            max_iter: parseInt($("#kan3").val()),
            random_state:parseInt($("#kan4").val()),
            copy_x:$("#kan5").val(),
            algorithm:$("#kan6").val()
        };
    }
    if(alg == 'PCA'){
        var params={
            copy:$("#fe0").val(),
            whiten:$("#fe1").val(),
            svd_solver: $("#fe2").val(),
            random_state: parseInt($("#fe3").val()),
        };
    }
    if(alg == 'AUTO_CLASS'){
        var params={
            time_left_for_this_task: parseInt($("#class0").val()),
            per_run_time_limit: parseInt($("#class1").val()),
        };
    }
    if(alg == 'AUTO_REG'){
        var params={
            time_left_for_this_task: parseInt($("#pred0").val()),
            per_run_time_limit: parseInt($("#pred1").val()),
        };
    }
    $.requestJSON({
      url: Urls.resolve('mlplatform_api_v1:task_add'),
      method: 'POST',
      data: {
        title: "test",
        algorithm: alg,
        params:params,
        dataset:dataset,
        label:alg_params,
        task_type:0
      },
      silentError: true,
      onSuccess: function(data){
          $.showModal({
              title: data.data.errCode + ': ' + data.data.errMsg,
              message: gettext('Create a task successfully, you can view it in the task list.')
          });
      },
      onError: function (data) {
          $.showModal({
              title: gettext('ERROR') + ' ' + data.data.errCode + ': ' + data.data.errMsg,
              message: gettext('An error has occurred! Please check your data and try again.')
          });
      },
    });
}
var params;
var text;
var dataset_id;
$(function () {
    dataset_show_all(1, null);
    $('#ds-search-btn').on('click', function () {
        text = $("#ds-search-text").val().trim();
        sort_show_all(1, null);
    });
    $("#ds-search-text").bind('keypress', function (event) {
    if (event.keyCode === 13) {
      $('#ds-search-btn').click();
    }
  });
    $("#btnSubmit").click(function () {
        var val = $('input:radio[name="iCheck"]').is(":checked");
        var lab = $('input:radio[name="radioInline"]').is(":checked");
        var list = $('input:radio[name="ra"]').is(":checked");
        var list1 = $('input:radio[name="ra"]:checked').val();
        var list2 = $(kan0).val();
        if (val == false) {
            $.showModal({
                title:gettext('Warning'),
                message: gettext('You have not selected a dataset yet!')
            });
        }
        else if (lab == false) {
            $.showModal({
                title:gettext('Warning'),
                message: gettext('You have not selected a label for the dataset yet!')
            });
        }
        else if(list == false) {
            $.showModal({
                title:gettext('Warning'),
                message: gettext('You have not selected a algorithm yet!')
            });
        }
        else
            param_submit();
    });
    $("#TaskSubmit").click(function () {
        var val = $('input:radio[name="iCheck"]').is(":checked");
        var lab = $('input:radio[name="radioInline"]').is(":checked");
        var list = $('input:radio[name="ra"]').is(":checked");
        var list1 = $('input:radio[name="ra"]:checked').val();
        var list2 = $(kan0).val();
        if (val == false) {
            $.showModal({
                title:gettext('Warning'),
                message: gettext('You have not selected a dataset yet!')
            });
        }
        else if (lab == false) {
            $.showModal({
                title:gettext('Warning'),
                message: gettext('You have not selected a label for the dataset yet!')
            });
        }
        else if(list == false) {
            $.showModal({
                title:gettext('Warning'),
                message: gettext('You have not selected your task type!')
            });
        }
        else
            param_submit();
    });
});
